package com.zhdl.modules.demo.aoptest;

import com.zhdl.modules.common.logging.service.OptRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Aspect
@Component
@RequiredArgsConstructor
@Slf4j
public class OptLogAspect {
    @Resource
    OptRecordService optRecordService;

    /**
     * 返回通知
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, OptLog controllerLog, Object jsonResult) {
        //调用处理日志的方法
    }

    /**
     * 异常通知
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(pointcut = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, OptLog controllerLog, Exception e) {

    }

    /**
     * 处理请求前执行，此方法旨在记录方法的开始时间。
     *
     * @param joinPoint     切点
     * @param controllerLog 一个注解对象，表示目标方法上标注的注解。这里用于判断方法是否应该被此切面处理。
     */
    @Before(value = "@annotation(controllerLog)")
    public void doBefore(JoinPoint joinPoint, OptLog controllerLog) {
        handleLog(joinPoint, controllerLog);
    }

    private void handleLog(JoinPoint joinPoint, OptLog controllerLog) {
        optRecordService.saveRecords(controllerLog.businessType() + controllerLog.title());
    }

}
